<template>
  <div class="study-room-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>自习室管理</span>
          <el-button type="primary" @click="handleAdd">添加自习室</el-button>
        </div>
      </template>
      
      <el-table :data="rooms" style="width: 100%">
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="location" label="位置" />
        <el-table-column prop="totalSeats" label="总座位数" />
        <el-table-column prop="availableSeats" label="可用座位" width="100" />
        <el-table-column label="轮播图" width="200">
          <template #default="scope">
            <el-image
              v-if="scope.row.images"
              style="width: 50px; height: 50px"
              :src="`http://localhost:8080/api${scope.row.images.split(';')[0]}`"
              :preview-src-list="scope.row.images.split(';').map(img => `http://localhost:8080/api${img}`)"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '开放' : '关闭' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleSeats(scope.row)">座位管理</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加自习室' : '编辑自习室'"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="form.location" />
        </el-form-item>
        <el-form-item label="总座位数" prop="totalSeats">
          <el-input-number v-model="form.totalSeats" :min="1" />
        </el-form-item>
        <el-form-item label="轮播图">
          <el-upload
            class="upload-demo"
            action="/api/admin/snacks/upload"
            :headers="uploadHeaders"
            list-type="picture-card"
            :limit="5"
            :file-list="imageList"
            :on-preview="handlePreview"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            multiple
          >
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">
              支持jpg/png文件，最多5张图片，每张不超过2MB
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-text="开放"
            inactive-text="关闭"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="seatsDialogVisible"
      :title="`座位管理 - ${currentRoom?.name || ''}`"
      width="80%"
    >
      <div class="seats-container">
        <div v-for="seat in seats" :key="seat.id" class="seat-item">
          <span class="seat-label">禁用</span>
          <el-switch
            v-model="seat.status"
            @change="() => handleSeatStatusChange(seat)"
            :active-value="1"
            :inactive-value="0"
          />
          <span class="seat-label">可用</span>
          <span class="seat-number">{{ seat.seatNumber }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

export default {
  name: 'StudyRoomManagement',
  setup() {
    const rooms = ref([])
    const seats = ref([])
    const dialogVisible = ref(false)
    const seatsDialogVisible = ref(false)
    const dialogType = ref('add')
    const formRef = ref(null)
    const currentRoom = ref(null)
    const imageList = ref([])
    const uploadHeaders = {
      Authorization: `Bearer ${localStorage.getItem('token')}`
    }
    const currentPage = ref(1)
    const pageSize = ref(10)

    const form = reactive({
      name: '',
      location: '',
      totalSeats: 1,
      status: 1,
      description: ''
    })

    const rules = {
      name: [{ required: true, message: '请输入自习室名称', trigger: 'blur' }],
      location: [{ required: true, message: '请输入位置', trigger: 'blur' }],
      totalSeats: [{ required: true, message: '请输入座位数', trigger: 'blur' }]
    }

    const loadRooms = async () => {
      try {
        const res = await request.get('/admin/study-rooms')
        if (res.code === 200) {
          rooms.value = res.data
          
          // 获取每个自习室的可用座位数
          for (const room of rooms.value) {
            try {
              // 获取该自习室的所有座位
              const seatsRes = await request.get(`/admin/study-rooms/${room.id}/seats`)
              if (seatsRes.code === 200) {
                // 计算可用座位数量（status为1且isOccupied为0的座位）
                const availableSeats = seatsRes.data.filter(seat => 
                  seat.status === 1
                ).length
                
                // 更新自习室对象的可用座位数
                room.availableSeats = availableSeats
              }
            } catch (error) {
              console.error(`获取自习室${room.id}座位失败:`, error)
              room.availableSeats = 0
            }
          }
        }
      } catch (error) {
        console.error('Failed to load study rooms:', error)
        ElMessage.error('加载自习室列表失败')
      }
    }

    const loadSeats = async (roomId) => {
      try {
        const res = await request.get(`/admin/study-rooms/${roomId}/seats`)
        seats.value = res.data
      } catch (error) {
        console.error('Failed to load seats:', error)
      }
    }

    const handleAdd = () => {
      dialogType.value = 'add'
      dialogVisible.value = true
      Object.assign(form, {
        id: undefined,
        name: '',
        location: '',
        totalSeats: 1,
        status: 1,
        description: '',
        images: ''
      })
      imageList.value = []
    }

    const handleEdit = (row) => {
      dialogType.value = 'edit'
      dialogVisible.value = true
      Object.assign(form, row)
      if (row.images) {
        imageList.value = row.images.split(';').map(url => ({
          url: `http://localhost:8080/api${url}`,
          name: url.split('/').pop()
        }))
      } else {
        imageList.value = []
      }
    }

    const handleSeats = async (row) => {
      currentRoom.value = row
      seatsDialogVisible.value = true
      await loadSeats(row.id)
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm('确定要删除该自习室吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await request.delete(`/admin/study-rooms/${row.id}`)
          ElMessage.success('删除成功')
          loadRooms()
        } catch (error) {
          console.error('Failed to delete study room:', error)
        }
      })
    }

    const handleSubmit = () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            console.log('提交前的form数据:', form)
            
            const submitData = { ...form }
            if (dialogType.value === 'add') {
              delete submitData.id
            }
            
            if (dialogType.value === 'add') {
              await request.post('/admin/study-rooms', submitData)
            } else {
              await request.put(`/admin/study-rooms/${form.id}`, submitData)
            }
            
            ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
            dialogVisible.value = false
            loadRooms()
          } catch (error) {
            console.error('Failed to submit:', error)
            ElMessage.error('操作失败')
          }
        }
      })
    }

    const handleSeatStatusChange = async (seat) => {
      try {
        await request.put(`/seats/admin/study-rooms/${currentRoom.value.id}/seats/${seat.id}`, {
          available: seat.status
        })
        ElMessage.success('座位状态更新成功')
        
        // 更新自习室的可用座位计数
        const availableSeats = seats.value.filter(s => s.status === 1).length
        if (currentRoom.value) {
          currentRoom.value.availableSeats = availableSeats
        }
      } catch (error) {
        console.error('Failed to update seat status:', error)
        seat.status = seat.status === 1 ? 0 : 1
        ElMessage.error('更新座位状态失败')
      }
    }

    const beforeUpload = (file) => {
      console.log('准备上传文件:', file)
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    }

    const handleUploadSuccess = (response, file) => {
      console.log('文件上传成功:', response)
      const imageUrl = response.data
      console.log('获取到的图片URL:', imageUrl)
      
      let currentImages = form.images ? form.images.split(';') : []
      
      currentImages.push(imageUrl)
      
      form.images = currentImages.join(';')
      
      if (!imageList.value) {
        imageList.value = []
      }
      imageList.value.push({
        url: `http://localhost:8080/api${imageUrl}`,
        name: imageUrl.split('/').pop()
      })
      
      console.log('当前图片列表:', imageList.value)
    }

    const handleRemove = (file, fileList) => {
      console.log('移除图片:', file)
      console.log('当前图片列表:', fileList)
      
      imageList.value = fileList
      form.images = fileList
        .map(file => {
          if (file.response?.data) {
            return file.response.data
          }
          return file.url.replace('http://localhost:8080/api', '')
        })
        .filter(Boolean)
        .join(';')
    }

    const handlePreview = (file) => {
      console.log('预览图片:', file)
      window.open(file.url || file.response.data.url)
    }

    loadRooms()

    return {
      rooms,
      seats,
      dialogVisible,
      seatsDialogVisible,
      dialogType,
      form,
      formRef,
      rules,
      handleAdd,
      handleEdit,
      handleSeats,
      handleDelete,
      handleSubmit,
      handleSeatStatusChange,
      imageList,
      uploadHeaders,
      beforeUpload,
      handleUploadSuccess,
      handleRemove,
      handlePreview,
      currentPage,
      pageSize,
      currentRoom
    }
  }
}
</script>

<style scoped>
.study-room-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.seats-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 20px;
  padding: 20px;
}

.seat-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.seat-number {
  font-size: 14px;
  color: #606266;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}
</style> 